/**
 * 上海中赢金融信息服务有限公司
 * Copyright (c) 2016-2026 hmc,Inc.All Rights Reserved.
 */
package com.sys.midware.rdb.sql.parser;

import java.util.List;

import com.sys.midware.logger.Logger;
import com.sys.midware.logger.LoggerFactory;
import com.sys.midware.rdb.sql.SQLType;

import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.delete.Delete;
import net.sf.jsqlparser.statement.insert.Insert;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.jsqlparser.statement.update.Update;
import net.sf.jsqlparser.util.TablesNamesFinder;

/**
 * sql解析工具类
 * 
 * @author mobing@b5m.com
 * @see com.gaoxin.ocean.utils.sql.parser.JSqlParserUtil
 * @version V0.0.1-SNAPSHOT, 2015-1-19 上午11:27:09
 * @description
 * 
 */
public class JSqlParserUtil {
	private final static Logger LOG = LoggerFactory.getLogger(JSqlParserUtil.class);

	public static Statement getStatement(String sql){
		Statement statement =null;
		SQLType type= SqlParserFactory.getSQLType(sql);
		try {
			if(SQLType.isInsert(type)){
				statement = (Insert)CCJSqlParserUtil.parse(sql);
			}else if(SQLType.isSelect(type)){
				statement = (Select)CCJSqlParserUtil.parse(sql);
			}else if(SQLType.isUpdate(type)){
				statement = (Update)CCJSqlParserUtil.parse(sql);
			}else if(SQLType.isDelete(type)){
				statement = (Delete)CCJSqlParserUtil.parse(sql);
			}
		} catch (JSQLParserException e) {
			LOG.error("",e);
		}
		
		return statement;
	}
	/**
	 * 获取表名List
	 * 
	 * @description {TODO}
	 * @param sql
	 * @return
	 */
	public static List<String> getTableList(String sql) {
		List<String> tableList = null;
		try {
			Statement statement = getStatement(sql);
			TablesNamesFinder tablesNamesFinder = new TablesNamesFinder();
			if (statement instanceof Select) {
				tableList = tablesNamesFinder.getTableList((Select) statement);
			} else if (statement instanceof Insert) {
				tableList = tablesNamesFinder.getTableList((Insert) statement);
			}else if (statement instanceof Update) {
				tableList = tablesNamesFinder.getTableList((Update) statement);
			}else if (statement instanceof Delete) {
				tableList = tablesNamesFinder.getTableList((Delete) statement);
			}
		} catch (Exception e) {
			LOG.error("sql 解析异常", e);
		}
		return tableList;
	}

}
